package services

import (
	"bytes"
	"context"
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"io/ioutil"
	"net/http"
	"strings"
	"wecom_rebot/common"
	"wecom_rebot/core"
	"wecom_rebot/models"
)

var ksSendSmsLogger *logrus.Logger

// InitKsSendSmsLogger 移除 init() 函数，改为显式初始化函数
func InitKsSendSmsLogger() {
	// 确保在 common 初始化后调用
	ksSendSmsLogger = core.InitLogger(common.LogsErrorMap[20])
}

type KsSendSmsServiceAnalyzeContent struct {
	AdvertiserUserId string
	AgentId          string
}
type getKsUserIdResponse struct {
	Result  int    `json:"result"`
	Message string `json:"message"`
	Data    struct {
		UserName          string `json:"userName"`
		UserId            string `json:"userId"`
		HeadUrl           string `json:"headUrl"`
		Phone             string `json:"phone"`
		Email             string `json:"email"`
		Banned            bool   `json:"banned"`
		NeedVerifySmsCode bool   `json:"needVerifySmsCode"`
		TestFlag          bool   `json:"testFlag"`
	} `json:"data"`
}

type sendSmsResponse struct {
	Code int `json:"code"`
	Data struct {
		Result       bool `json:"result"`
		CheckSmsCode bool `json:"check_sms_code"`
	} `json:"data"`
	Msg string `json:"msg"`
}

type DeftHandSendSmsService struct {
}

func (s *DeftHandSendSmsService) Handle(msgId int, subjectName, roomId string, content []string, jobId uint64) error {
	strPj := "-----------------------------------"

	var msg = &models.Msg{}

	fmt.Println("ksSendSmsLogger", "原始结构Id：", msgId)
	// 获取数据
	err := common.DB.Where("id = ?", msgId).First(&msg).Error
	if err != nil {
		ksSendSmsLogger.Error("腾讯获取数据失败", common.LogsErrorMap[common.MysqlError], msgId, err)
		return err
	}

	ksSendSmsLogger.Info("ksSendSmsLogger", "原始结构：", content)

	// 处理需要的数据结构
	result, err := s.analyzeContent(content)
	if err != nil {
		ksSendSmsLogger.Error(err)
		return err
	}

	ksSendSmsLogger.Info("ksSendSmsLogger", result)

	// 移除功能行
	msg.Content = RemoveTitle(msg)
	fmt.Println("移除后的结构：", msg, "广告主信息：", content)

	rdb := core.InitRedis(13)
	ctx := context.Background()

	cookies, _ := rdb.Get(ctx, "laravel_database_ks_adv_cookies").Result()
	trace, _ := rdb.Get(ctx, "laravel_database_ks_adv_trace").Result()

	// 解析广告主用户ID
	var advertiserUserId string
	// 如果 advertiser_user_id 中带有 @ 就判定为邮箱
	if strings.Contains(result.AdvertiserUserId, "@") {
		// 通过快手去获取 userid
		userResponse, err := s.getKsUserId(result.AdvertiserUserId, cookies, trace)
		if err != nil {
			ksSendSmsLogger.Errorf("发送消息失败: %v", err)
			return errors.New("获取失败：" + err.Error())
		}
		advertiserUserId = userResponse.Data.UserId
	} else {
		// 直接转换为int64
		advertiserUserId = result.AdvertiserUserId
	}

	// 获取对应后台ID的token
	token, err := getDeftHandToken(result.AgentId)
	if err != nil {
		return err
	}

	err = s.SendSmsRequest(result.AgentId, advertiserUserId, token)
	if err != nil {
		return err
	}

	err = BendiSendText(msg.Content+"\n"+strPj+"\n短信发送成功：请注意查收在15分钟内有效\n快手用户userid："+advertiserUserId, roomId, msg.Sender)
	if err != nil {
		return errors.New("发送消息失败")
	}
	return nil
}

func (s *DeftHandSendSmsService) SendSmsRequest(agentId, advertiserUserId, token string) error {
	sendUrl := "https://ad.e.kuaishou.com/rest/openapi/gw/agent/v1/sms_code/send"

	data := make(map[string]interface{})

	data["advertiser_user_id"] = advertiserUserId
	data["agent_id"] = agentId

	var req sendSmsResponse

	err := KsSendCurlRequest(sendUrl, "POST", token, data, nil, &req)
	if err != nil {
		ksSendSmsLogger.Errorf("发送短信失败: %v", err)
		return errors.New("发送短信失败1：" + err.Error())
	}

	ksSendSmsLogger.Info("发送短信返回结果:", req)

	if req.Code != 0 {
		ksSendSmsLogger.Errorf("发送短信失败: %v", req)
		return errors.New("发送短信失败2：" + req.Msg)
	}

	if req.Data.CheckSmsCode {
		if !req.Data.Result {
			ksSendSmsLogger.Errorf("发送短信失败3: %v", req.Msg)
			return errors.New("发送短信失败3：" + req.Msg)
		}
	}

	return nil
}

func (s *DeftHandSendSmsService) getKsUserId(email, cookies, trace string) (*getKsUserIdResponse, error) {

	userUrl := fmt.Sprintf("https://uc.e.kuaishou.com/rest/customer/common/kwai-user-search?condition=%s", email)

	var req getKsUserIdResponse
	err := s.SendCurlRequest(userUrl, nil, cookies, "GET", trace, &req)
	if err != nil {
		ksSendSmsLogger.Errorf("获取快手用户ID失败: %v", err)
		return nil, fmt.Errorf("获取快手用户ID失败: %w", err)
	}
	ksSendSmsLogger.Infof("获取快手用户ID成功: %+v", req)
	// 检查返回结果
	if req.Result != 0 {
		ksSendSmsLogger.Errorf("获取快手用户ID失败，错误: %v, 错误信息: %s", req, req.Message)
		return nil, fmt.Errorf("获取快手用户ID失败: %s", req.Message)
	}

	return &req, nil
}

// SendCurlRequest 发送HTTP请求到快手API
func (s *DeftHandSendSmsService) SendCurlRequest(url string, postData map[string]interface{}, cookies, method, trace string, result interface{}) error {
	var req *http.Request
	var err error

	// 创建HTTP请求
	if postData != nil && len(postData) > 0 {
		// POST请求处理
		jsonData, err := json.Marshal(postData)
		if err != nil {
			return fmt.Errorf("JSON序列化失败: %w", err)
		}

		req, err = http.NewRequest(strings.ToUpper(method), url, bytes.NewBuffer(jsonData))
		if err != nil {
			return fmt.Errorf("创建请求失败: %w", err)
		}
	} else {
		// GET请求或其他无数据请求
		req, err = http.NewRequest(strings.ToUpper(method), url, nil)
		if err != nil {
			return fmt.Errorf("创建请求失败: %w", err)
		}
	}

	// 设置HTTP版本
	req.Proto = "HTTP/1.1"
	req.ProtoMajor = 1
	req.ProtoMinor = 1

	// 设置请求头部
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Cookie", cookies)
	req.Header.Set("ktrace-str", trace)

	// 创建HTTP客户端（跳过SSL验证，与原PHP代码保持一致）
	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("发送请求失败: %w", err)
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("读取响应失败: %w", err)
	}

	// 解析响应为结构体
	err = json.Unmarshal(body, &result)
	if err != nil {
		ksSendSmsLogger.Errorf("解析快手响应失败：%s, 错误: %v", string(body), err)
		return fmt.Errorf("解析响应失败: %w", err)
	}

	// 记录日志（如果需要）
	ksSendSmsLogger.Infof("快手返回结果：%s", string(body))

	return nil
}

// analyzeContent 解析内容为广告主信息数组
func (s *DeftHandSendSmsService) analyzeContent(content []string) (*KsSendSmsServiceAnalyzeContent, error) {
	// 初始化结果变量
	var advertiserUserId string
	var agentId string

	// 遍历内容行
	for _, line := range content {
		// 快手ID
		if strings.HasPrefix(line, "快手ID:") {
			advertiserUserId = strings.TrimSpace(strings.TrimPrefix(line, "快手ID:"))
		}
		// 代理商ID
		if strings.HasPrefix(line, "代理商ID:") {
			agentId = strings.TrimSpace(strings.TrimPrefix(line, "代理商ID:"))
		}
	}
	if advertiserUserId == "" {
		return nil, fmt.Errorf("快手ID不能为空")
	}

	if agentId == "" {
		return nil, fmt.Errorf("代理商ID不能为空")
	}

	return &KsSendSmsServiceAnalyzeContent{
		AdvertiserUserId: advertiserUserId,
		AgentId:          agentId,
	}, nil
}
